﻿using CYQ.Data;
using CYQ.Data.Table;
using CYQ.Data.Tool;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace DBCheck
{
    public partial class Form_NewestDB : Form
    {
        string sqlitestr = "Data Source=dbinfo.db;failifmissing=false;";
        public Form_NewestDB()
        {
            InitializeComponent();
        }

        private void btn_conn_Click(object sender, EventArgs e)
        {
            CYQ.Data.Cache.CacheManage.LocalInstance.Clear();
            string dbname = txt_name.Text.Trim();
            string sqlconnstr = txt_conn.Text;
            string sqlitestr = "Data Source=dbinfo.db;failifmissing=false;";
            bool result = DBTool.TestConn(sqlconnstr);//检测数据库链接是否正常 AppConfig.DB.DefaultConn
            OutMsg("数据库链接：" + result);
            if (!result)
            {
                return;
            }
            OutMsg("-----------------------------------------");
            string databaseName;
            Dictionary<string, string> tables = DBTool.GetTables(sqlconnstr, out databaseName);//读取所有表
            if (string.IsNullOrEmpty(databaseName)==false && dbname=="")
            {
                dbname = databaseName;
            }
            using (MAction action = new MAction(TableNames.dbinfo, sqlitestr))
            {
                if (!action.Exists(string.Format("dbname='{0}'", dbname)))
                {
                    action.Set(dbinfo.dbname, dbname);
                    action.Set(dbinfo.update, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                    action.Insert();
                }
                else
                {
                    if (MessageBox.Show(string.Format("已经存在模板：（{0}） 是否继续？",dbname), "提示", MessageBoxButtons.YesNo) != DialogResult.Yes)
                    {
                        return;
                    }
                }
            }
            if (tables != null)
            {
                OutMsg("数据库:" + databaseName);
                foreach (KeyValuePair<string, string> item in tables)
                {
                    OutMsg("表:" + item.Key + " 说明：" + item.Value);
                    using (MAction action = new MAction(TableNames.tableinfo, sqlitestr))
                    {
                        if (!action.Exists(string.Format("dbname='{0}' and tablename='{0}'", dbname, item.Key)))
                        {
                            action.Set(tableinfo.dbname, dbname);
                            action.Set(tableinfo.tablename, item.Key);
                            action.Set(tableinfo.note, item.Value);
                            action.Set(tableinfo.update, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                            action.Insert();
                        }
                    }
                    MDataColumn mdc = DBTool.GetColumns(item.Key, sqlconnstr);//读取所有列
                    using (MAction action = new MAction(TableNames.Colinfo, sqlitestr))
                    {
                        foreach (MCellStruct ms in mdc)
                        {
                            if (!action.Exists(string.Format("dbname='{0}' and tablename='{1}' and columnname='{2}'", databaseName, item.Key, ms.ColumnName)))
                            {
                                OutMsg("  列:" + ms.ColumnName + " SqlType：" + ms.SqlType);
                                action.Set(Colinfo.dbname, dbname);
                                action.Set(Colinfo.tableName, item.Key);
                                action.Set(Colinfo.columnName, ms.ColumnName);
                                action.Set(Colinfo.note, ms.Description);
                                action.Set(Colinfo.sqlType, ms.SqlType);
                                action.Set(Colinfo.MaxSize, ms.MaxSize);
                                action.Set(Colinfo.isPrimaryKey, ms.IsPrimaryKey);
                                action.Set(Colinfo.isCanNull, ms.IsCanNull);
                                action.Set(Colinfo.isAutoIncrement, ms.IsAutoIncrement);
                                action.Set(Colinfo.defaultValue, ms.DefaultValue);
                                action.Set(Colinfo.update, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                                action.Insert();
                            }
                        }
                    }
                }
            }
            else
            {
                OutMsg("该数据库没有此表结构!");
            }
            //更新时间
            using (MAction action = new MAction(TableNames.dbinfo, sqlitestr))
            {                
                {
                    action.Set(dbinfo.dbname, dbname);
                    action.Set(dbinfo.update, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                    action.Update();
                }
            }
            OutMsg("---------------------处理完成--------------------");
            Loaddbinfo();
        }
        private void OutMsg(string v)
        {
            txt_log.AppendText(v + "\r\n");
        }

        private void cb_dbinfo_SelectedIndexChanged(object sender, EventArgs e)
        {
            MDataTable dt;
            switch (cb_dbinfo.Text)
            {
                case "数据库":
                    using (MAction action = new MAction(TableNames.dbinfo, sqlitestr))
                    {
                        dt = action.Select();
                    }
                    dt.Bind(dataGridView1);
                    break;
                case "表":
                    using (MAction action = new MAction(TableNames.tableinfo, sqlitestr))
                    {
                        dt = action.Select();
                    }
                    dt.Bind(dataGridView1);
                    break;
                case "字段":
                    using (MAction action = new MAction(TableNames.Colinfo, sqlitestr))
                    {
                        dt = action.Select();
                    }
                    dt.Bind(dataGridView1);
                    break;
                default:
                    break;
            }
        }

        private void btn_del_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("是否删除？","提示",MessageBoxButtons.YesNo)!=DialogResult.Yes)
            {
                return;
            }
            using (MAction action = new MAction(TableNames.dbinfo, sqlitestr))
            {
                action.Delete(string.Format("dbname='{0}'",cb_db.Text));
            }
            using (MAction action = new MAction(TableNames.tableinfo, sqlitestr))
            {
                action.Delete(string.Format("dbname='{0}'", cb_db.Text));
            }
            using (MAction action = new MAction(TableNames.Colinfo, sqlitestr))
            {
                action.Delete(string.Format("dbname='{0}'", cb_db.Text));
            }
            Loaddbinfo();            
            OutMsg("删除完成！");
        }

        private void Form_NewestDB_Load(object sender, EventArgs e)
        {
            Loaddbinfo();
        }

        private void Loaddbinfo()
        {
            using (MAction action = new MAction(TableNames.dbinfo, sqlitestr))
            {
                var dt = action.Select();
                cb_db.DisplayMember = "dbname";
                cb_db.ValueMember = "update";
                cb_db.DataSource = dt.ToDataTable();
                cb_db.Text = "";
            }
        }
    }
}
